import {
    chManager,
    DefalutConfig,
    DelayType,
    DSP,
    EqChart,
    HID,
    myToast,
    setHid,
    showDropdown,
    SourceType
} from '../../node_modules/electron-cc-kit/index.js';
const bg_char = document.getElementById('bg_char_div');
const bg_eq = document.getElementById('bg_eq_div');
const bg_other = document.getElementById('bg_other_div');
const btn_person = document.getElementById('btn_person');
const btn_setting = document.getElementById('btn_setting');
const btn_gain = document.getElementById('btn_gain');
const btn_freq = document.getElementById('btn_freq');
const btn_q = document.getElementById('btn_q');
const btn_ms = document.getElementById('delay_ms_button');
const btn_cm = document.getElementById('delay_cm_button');
const btn_inch = document.getElementById('delay_inch_button');
const ch_setup_dropdown = document.getElementById('ch-setup-dropdown');
const ch_setup_dropleft = document.getElementById('ch-setup-dropleft');
const pass_dropdown = document.getElementById('pass-type-dropdown');
const slope_dropdown = document.getElementById('slope-dropdown');
const save_dropdown = document.getElementById('save-dropdown');
const load_dropdown = document.getElementById('load-dropdown');
const reset_dropdown = document.getElementById('reset-dropdown');
const setting_dropdown = document.getElementById('setting-dropdown');
const preset_dropleft = document.getElementById('preset-dropleft');
const noise_dropdown = document.getElementById('noise-dropdown');
const toggleState = (el, state = 'selected', equal = false) => equal ? el.classList.toggle(`${state}`) : el.classList.remove(`${state}`);
const toggleWarning = (el, equal = false) => toggleState(el, 'warning', equal);
const toggleSelected = (el, equal = false) => toggleState(el, 'selected', equal);
const addSelected = (el, add) => {
    if (!el.classList.contains('selected') && add) {
        el.classList.add('selected');
    }
    if (!add) {
        el.classList.remove('selected');
    }
}
const config = new DefalutConfig({ max_delay: 10, startBytesIndex: 3 });
chManager.config = config;
let effectIndex = -1;
const origin_map = [{ 'Hi.level': SourceType.rca }, { 'AUX': SourceType.aux }, { 'BT/USB': SourceType.bt }, { 'Optical': SourceType.optical }, { 'Coaxial': SourceType.coaxial }];

setHid();
HID.getHidDevices();
HID.listenerHidDeviceState();
const eqChart = new EqChart('bg_char_div', {
    backgroundColor: '#1C1C1E',
    gridColor: '#3A3A3C',
    textColor: '#C7C7CC',
    onChange: () => {
        updateEQ();
    }
});

var is_gain = true;
var is_freq = false;
var is_q = false;
document.addEventListener('DOMContentLoaded', () => {
    navActions();
    addEQItems();
    delayActions();

    addDSPChannelItems();
    addHighLowPassItems(true);
    addHighLowPassItems(false);
    addDbItems();
    addMasterDbItems();
    addSumItems();

    ///点击空白处隐藏下拉框
    document.addEventListener('click', documentClick);

    ///点击ml_message类的弹窗空白，隐藏弹窗
    document.querySelectorAll('.ml_message').forEach((e, index) => e.addEventListener('click', (event) => hiddenAlert(e, event)));
    // loadCustom({ selector: '[delay-input]', defaultPath: 'delay_input.html', });
    // loadCustom({ selector: '[delay-horn]', defaultPath: 'horn_button.html' });

    // 全局监听状态更新
    window.addEventListener('hid-status-change', (event) => {
        const { connected, device } = event.detail;
        const linkBtn = document.getElementById('nav_link');
        if (connected) {
            linkBtn.classList.remove('warning');
            linkBtn.classList.toggle('selected');
            DSP.loadDevice(500, {
                completion: () => {
                    updateAll();
                    console.log('=======================>完成了');
                }
            });
        } else {
            linkBtn.classList.toggle('warning');
            linkBtn.classList.remove('selected');
        }
        linkBtn.querySelector('.label').textContent = connected ? 'Linked' : 'Not linked';
    });
});

function navActions() {
    ///噪门
    const level_list = noise_dropdown.querySelectorAll('li button');
    level_list.forEach(($0) => toggleExclusiveSelected(level_list[chManager.noise], level_list));
    const nav_noise = document.querySelector('nav #nav_left #nav_noise .label');
    nav_noise.textContent = chManager.noise === 0 ? 'Noise' : `level${chManager.noise}`;

    btn_person.addEventListener('click', () => {
        // showMessage('person');
        documentClick();
        toggleSelected(btn_person);
    });

    btn_setting.addEventListener('click', () => {
        documentClick();
        toggleSelected(btn_setting);
        showSettingDropMenu(btn_setting);
    });

    // 使用事件委托处理 nav_a 的点击事件
    const navLeft = document.getElementById('nav_left');
    const list = navLeft.querySelectorAll('.nav_a');
    let filteredList = Array.from(list).filter(nav => nav.id !== 'nav_link');
    navLeft.addEventListener('click', (event) => {
        const anchor = event.target.closest('.nav_a');
        if (!anchor) return;

        event.preventDefault();
        event.stopPropagation();
        const label = anchor.querySelector('.label');
        const text = label?.textContent.trim();
        const arrow = anchor.querySelector('.icon_arrow');
        if (text !== 'Linked' && text !== 'Not linked') {
            hiddenDropdown();
            filteredList = Array.from(list).filter(nav => nav.id !== 'nav_link');
            filteredList = filteredList.filter((nav) => (chManager.isbyPass === false) || anchor === nav || (chManager.isbyPass === true && nav.id !== 'nav_bypass'));
            toggleExclusiveSelected(anchor, filteredList);
        }
        if (!anchor.classList.contains('selected') && anchor.id != 'nav_bypass') {
            return;
        }
        switch (text) {
            case 'Linked':
            case 'Not linked':
                // toggleWarning(anchor, label.textContent == text);
                // label.textContent = anchor.classList.contains('warning') ? 'Not linked' : 'Linked';
                break;
            case 'Setup':
                document.getElementsByClassName("ml_message")[0].style.display = "block";
                break;
            case 'Save':
                showSaveDropMenu(anchor);
                break;
            case 'Load':
                showLoadDropMenu(anchor);
                break;
            case 'ResetEQ':
                showResetDropMenu(anchor);
                break;
            case 'Bypass':
            case 'Restore':
                DSP.byPassorRestore();
                label.textContent = chManager.isbyPass ? 'Restore' : 'Bypass';
                updateEQ();
                break;
            case 'Noise':
            case 'level1':
            case 'level2':
            case 'level3':
            case 'level4':
            case 'level5':
            case 'level6':
            case 'level7':
            case 'level8':
                showNoiseDropMenu(anchor);
        }
    });
}


//添加eqitem
function addEQItems() {
    // gain按钮
    btn_gain.addEventListener('click', () => {
        [btn_gain, btn_freq, btn_q].forEach(($0) => addSelected($0, $0 === btn_gain));
        is_gain = true;
        is_freq = false;
        is_q = false;
        updateEQ();
    })

    // freq按钮
    btn_freq.addEventListener('click', () => {
        [btn_gain, btn_freq, btn_q].forEach(($0) => addSelected($0, $0 === btn_freq));
        is_gain = false;
        is_freq = true;
        is_q = false;
        updateEQ();
    });

    ///Q值
    btn_q.addEventListener('click', () => {
        [btn_gain, btn_freq, btn_q].forEach(($0) => addSelected($0, $0 === btn_q));
        is_gain = false;
        is_freq = false;
        is_q = true;
        updateEQ();
    })
    initEQItems();
    btn_gain.click();
}

///初始化eqitem
function initEQItems() {
    is_gain = btn_gain.classList.contains('selected');
    is_freq = btn_freq.classList.contains('selected');
    is_q = btn_q.classList.contains('selected');

    // 清除上一次构建的 eq_item
    document.querySelectorAll('#bg_eq_div .eq_item').forEach(item => item.remove());
    const template = document.getElementById('eq_template');
    const current_ch = chManager.current_chlist[0];
    current_ch.sign_list.forEach((sign, index) => {
        const clone = template.content.cloneNode(true);
        const eqItem = clone.querySelector('.eq_item');
        const eq_num = clone.querySelector('.eq_number');
        const eq_slider = clone.querySelector('.eq_slider');
        const bg_eq_num = clone.querySelector('.bg_eq_num');
        const eq_db = clone.querySelector('.eq_db_input');
        const eq_freq = clone.querySelector('.eq_freq_input');
        const eq_q = clone.querySelector('.eq_q_input');

        eqItem.id = `eq_item_${index}`;
        eq_num.id = `eq_num_${index}`;
        eq_slider.id = `eq_slider_${index}`;
        bg_eq_num.id = `bg_eq_num_${index}`;
        eq_db.id = `eq_db_${index}`;
        eq_freq.id = `eq_freq_${index}`;
        eq_q.id = `eq_q_${index}`;
        eq_db.value = sign.gain;
        eq_db.max = sign.max_gain;
        eq_db.min = sign.min_gain;

        eq_q.value = sign.q;
        eq_q.max = sign.max_q;
        eq_q.min = sign.min_q;

        eq_num.textContent = `${index + 1}`;
        bg_eq.appendChild(clone);
        setSign(sign);

        eq_slider.oninput = function (event) {
            if (is_gain) {
                DSP.updateGain(index, eq_slider.value)
                updateEQ_DB(index);
            } else if (is_freq) {
                DSP.updateEQFreq(index, eq_slider.value);
                updateEQ_Freq();
            } else {
                DSP.updateQ(index, eq_slider.value);
                updateEQ_Q();
            }
            updateEQ_Slider();
            changeSelectCH(chManager.current_chlist[0]);
            setSign(chManager.current_chlist[0].sign_list[index], is_freq);
            ///更新其他item的颜色
            document.querySelectorAll('.eq_number').forEach(numElem => {
                numElem.style.backgroundColor = numElem == eq_num ? '#2147ad' : 'transparent';
                numElem.style.boxShadow = numElem == eq_num ? '0 0 5px 2px #0B84FF' : 'none';
            });
            // 背景阴影
            document.querySelectorAll('.bg_eq_num').forEach(bgeqElem => {
                bgeqElem.style.boxShadow = bgeqElem == bg_eq_num ? '0 0 5px 2px #0B84FF' : 'none';
            });
        };

        ///滑动结束
        eq_slider.addEventListener('change', () => setSign(chManager.current_chlist[0].sign_list[index], false));

        ///gain
        eq_db.onfocus = function () {

        }

        eq_db.oninput = function (e) {
            let value = e.target.value;
            const gain = parseFloat(value);
            DSP.updateGain(index, gain);
            updateEQ_Slider();
        }

        eq_db.onblur = function (e) {
            let value = e.target.value;
            const gain = Math.min(Math.max(parseFloat(value), sign.min_gain), sign.max_gain);
            DSP.updateGain(index, gain);
            updateEQ_Slider();
            updateEQ_DB();
        }

        eq_freq.onfocus = function (e) { e.target.value = sign.freq };

        eq_freq.oninput = function (e) {
            const value = Math.max(0, parseInt(e.target.value));  // \D 匹配非数字，全部替换为空
            DSP.updateEQFreq(index, value);
            updateEQ_Slider();
            updateEQ_Freq();
        }
        eq_freq.onblur = function (e) {
            const value = e.target.value.replace(/\D/g, '');  // \D 匹配非数字，全部替换为空
            const freq = Math.min(Math.max(sign.min_freq, value), sign.max_freq);
            DSP.updateEQFreq(index, freq);
            updateEQ_Slider();
            updateEQ_Freq();
        }

        eq_q.onfocus = function () { }

        eq_q.oninput = function (e) {
            const value = e.target.value;

            // 验证是否是有效的数字（包括正负整数和小数）
            if (!/^\d+(\.\d+)?$/.test(e.target.value) && e.target.value !== '') {
                // 如果不是有效格式，恢复上一个有效值
                e.target.value = e.target.dataset.lastValid || '0';
            } else {
                // 存储当前有效值
                e.target.dataset.lastValid = e.target.value;
            }
            const q = parseFloat(value);
            DSP.updateQ(index, q);
            updateEQ_Slider();
        }
        eq_q.onblur = function (e) {
            const value = e.target.value;
            const q = Math.min(Math.max(parseFloat(value), sign.min_q), sign.max_q);
            DSP.updateQ(index, q);
            updateEQ_Slider();
            updateEQ_Q();
        }
    });

    function setSign(sign, showAll) {
        document.getElementById(`eq_db_${sign.index}`).value = sign.gain;
        document.getElementById(`eq_freq_${sign.index}`).value = `${sign.freq}`;
        document.getElementById(`eq_q_${sign.index}`).value = sign.q;
    }
}


///延迟的相关呢方法
function delayActions() {
    ///ms/cm/inch
    const delay_type_div = document.getElementById('delay_type_div');
    const btn_list = delay_type_div.querySelectorAll('.gradient-button');
    const list = [DelayType.ms, DelayType.cm, DelayType.inch]
    const matchedIndex = list.findIndex(el => el === chManager.delayType);
    addSelected(btn_list[matchedIndex], true);

    btn_list.forEach((btn, index) => {
        btn.addEventListener('click', () => {
            chManager.delayType = list[index];
            chManager.chlist.forEach(($0, index) => setdelayitems(index));
            btn_list.forEach((el) => addSelected(el, btn == el));
        });
    });

    ///添加喇叭
    addHornItems();
    function addHornItems() {
        const top_horn_div = document.getElementById('top_horn_div');
        const bottom_horn_div = document.getElementById('bottom_horn_div');
        const righ_horn_div = document.getElementById('middle_horn_right_div');
        const left_horn_div = document.getElementById('middle_horn_left_div');
        const template = document.getElementById('horn_template');


        ///
        chManager.chlist.forEach((ch, index) => {
            const clone = template.content.cloneNode(true);
            const hornItem = clone.querySelector('.horn_item_div');
            const input = clone.querySelector('.input-delay');
            const horn = clone.querySelector('.horn-delay');
            const rippleContainer = horn.querySelector('.ripple-container');

            hornItem.id = `horn_item_${index}`;
            input.id = `delay_input_${index}`;
            horn.id = `delay_horn_${index}`;
            rippleContainer.id = `horn_ripple_${index}`;

            // input.value = ch.delay;
            input.style.fontSize = `14px`;
            input.onfocus = function () {
                // 添加三个波纹 div
                for (let i = 0; i < 3; i++) {
                    const ripple = document.createElement('div');
                    ripple.classList.add('ripple');
                    rippleContainer.appendChild(ripple);
                }
                changeSelectCH(ch);
            }

            input.onblur = function (e) {
                setdelayitems(index);
                // 移除所有波纹 div
                rippleContainer.innerHTML = '';
                // switch (chManager.delayType) {
                //     case DelayType.ms:
                //         input
                //         break;
                // case DelayType.cm:
                //     break;
                //     case DelayType.inch:
                //         break;
                //     default:
                //         break;
                // }
            }
            input.oninput = function (e) {
                let value = e.target.value;
                // ✅允许只输入数字和一个小数点
                if (!/^\d*\.?\d*$/.test(value)) {
                    // 移除非法字符
                    e.target.value = value.replace(/[^\d.]/g, '')
                        .replace(/\.{2,}/g, '.')     // 只保留一个小数点
                        .replace(/^(\d*\.\d*?)\..*$/, '$1'); // 只保留第一次出现的小数点
                }
                DSP.updateDelay(index, value);
                // setdelayitems(index);
                ///✅ 禁止首位输入小数点（只允许 0.xx 而非 .xx）：
                // if (/^\./.test(value)) {
                //     e.target.value = '0' + e.target.value;
                // }
                ///✅ 限制最多 2 位小数：
                // e.target.value = e.target.value.replace(/^(\d+\.\d{0,2}).*$/, '$1');
            }


            ///喇叭波纹
            let isSelected = false;
            horn.onclick = function () { }

            if (index === chManager.chlist.length - 2) {
                top_horn_div.appendChild(hornItem);
            }
            else if (index == chManager.chlist.length - 1) {
                bottom_horn_div.appendChild(hornItem);
            }
            else if ((index + 1) % 2 === 1) {
                left_horn_div.appendChild(hornItem);
            }
            else if ((index + 1) % 2 === 0) {
                righ_horn_div.appendChild(hornItem);
            }

            setdelayitems(index);
        });
    }
    ///设置item的值
    function setdelayitems(index) {
        const input = document.getElementById(`delay_input_${index}`);
        input.value = DSP.getDelayValue(index);
    }
}


///添加chnannel相关方法
async function addDSPChannelItems() {
    ///ch
    const bg_ch_items = document.querySelector('.bg_ch_items:not(.group)');
    const ch_template = document.getElementById('template_ch');
    const dropdown_left_container = document.getElementById('dropdown-menu-container');

    ///ch
    await DSP.getChCustomName();
    chManager.chlist.forEach((ch, index) => {
        const clone2 = ch_template.content.cloneNode(true);
        const bg_ch_item = clone2.querySelector('.ch_item_div');
        const ch_name = clone2.querySelector('.ch_num');
        const ch_color = clone2.querySelector('.ch_color');
        const ch_more = clone2.querySelector('.pulldown_btn');

        ch_name.id = `ch_name_${index}`;
        ch_color.id = `ch_color_${index}`;
        ch_more.id = `ch_more_${index}`;
        ch_more.firstChild.textContent = ch.custom_name || '空';

        ch_name.textContent = ch.name;
        ch_color.style.background = ch.hex_line;

        bg_ch_items.appendChild(bg_ch_item);

        // 配置菜单数据
        const menuConfig = {
            '前置': { '左': ['高频', '中频', '中高频', '中低频', '低频', '全频'], '右': ['高频', '中频', '中高频', '中低频', '低频', '全频'] },
            '后置': { '左': ['高频', '中频', '中高频', '中低频', '低频', '全频'], '右': ['高频', '中频', '中高频', '中低频', '低频', '全频'] },
            '中置': { '前': ['高频', '中频', '中高频', '全频'], '后': ['高频', '中频', '中高频', '全频'] },
            '顶置': { '前': ['左', '右'], '后': ['左', '右'] },
            '超低': { '': ['左超低频', '右超低频', '超低频'] },
            '环绕': { '': ['左环绕', '右环绕'] }
        };
        ///点击弹出下拉框
        ch_more.addEventListener('click', (e) => {
            e.stopPropagation();
            documentClick();
            showDropdown(ch_more, ch_setup_dropdown, 'bottom');
            dropMenuHandle(ch_setup_dropdown, async (text, event, el) => {
                if (event.click && text === '空') {
                    DSP.setChCustomName(ch, text);
                    ch_more.firstChild.textContent = ch.custom_name || text;
                    return;
                }

                if (!event.in || text === '空') return;

                const menu_data = menuConfig[text] ? [menuConfig[text]] : [];
                dropdown_left_container.innerHTML = '';

                // 渲染菜单
                menu_data.forEach(obj => {
                    Object.entries(obj).forEach(([key, items]) => {
                        if (key) {
                            const li = document.createElement('li');
                            li.innerHTML = `<span>${key}</span>`;
                            dropdown_left_container.appendChild(li);
                        }

                        items.forEach(item => {
                            const li = document.createElement('li');
                            const button = document.createElement('button');
                            button.textContent = item;
                            button.dataset.supertext = key;
                            li.appendChild(button);
                            dropdown_left_container.appendChild(li);
                        });
                    });
                });

                showDropdown(el, ch_setup_dropleft, 'right');
                ch_setup_dropleft.style.display = 'block';

                dropMenuHandle(ch_setup_dropleft, (text2, event2, el2) => {
                    if (event2.click && !Object.keys(menu_data[0]).includes(text2)) {
                        const supertext = el2.dataset.supertext || '';
                        let name = '';

                        if (['前置', '后置', '中置'].includes(text)) {
                            name = supertext + text.slice(0, 1) + text2;
                        } else if (text === '顶置') {
                            name = text2 + supertext + text;
                        } else {
                            name = text2;
                        }

                        DSP.setChCustomName(ch, name);
                        ch_more.firstChild.textContent = ch.custom_name || '空';
                    }
                });
            });
        });

        ///选择通道
        ch_name.addEventListener('click', () => {
            changeSelectCH(ch);
        });

        bg_ch_item.addEventListener('mouseleave', () => {
            ch_setup_dropleft.style.display = 'none';
        });
    });

    ///group
    const bg_group_items = document.querySelector('.bg_ch_items.group');
    const group_template = document.getElementById('template_group');
    chManager.group_list.forEach((item, index) => {
        const clone1 = group_template.content.cloneNode(true);
        const group = clone1.querySelector('.btn_group');
        group.id = `btn_group_${index}`;
        bg_group_items.appendChild(group);
        group.onclick = function () {
            changeSelectGroup(index);
        };
    });

    const resizeObserver = new ResizeObserver((entries) => {
        const h = bg_group_items.getBoundingClientRect().height;
        const ch_h = document.querySelectorAll('.ch_item_div')[0].getBoundingClientRect().height;
        const gap = (h - ch_h * chManager.chlist.length) / (chManager.chlist.length - 1);
        const group_list = document.querySelectorAll('.btn_group');
        const group_h = group_list[0].getBoundingClientRect().height;

        document.querySelectorAll('.btn_group').forEach((e, i) => {
            const top = (2 * i + 1) * ch_h + (2 * i + 0.5) * gap - group_h / 2;
            e.style.top = top + 'px';
        });
    });

    resizeObserver.observe(bg_group_items); // 监听该元素
}

function updateAll() {
    updateEQ();
    updatePASS(true, { isall: true });
    updatePASS(false, { isall: true });
    updateDB({ isall: true });
    updateDelay();
    updateMasterAll();
    updateSumAlert();
}

function updateEQ() {
    updateEQ_Slider();
    updateEQ_DB();
    updateEQ_Freq();
    updateEQ_Q();
}
function updateEQ_Slider() {
    chManager.current_chlist[0].sign_list.forEach((sign, i) => {
        const eq_slider = document.getElementById(`eq_slider_${i}`);
        if (is_gain) {
            eq_slider.max = sign.max_gain;
            eq_slider.min = sign.min_gain;
            eq_slider.value = sign.gain;
            eq_slider.step = 1;
        } else if (is_freq) {
            eq_slider.max = sign.max_freq;
            eq_slider.min = sign.min_freq;
            eq_slider.value = sign.freq;
            eq_slider.step = 1;
        } else {
            eq_slider.max = sign.max_q;
            eq_slider.min = sign.min_q;
            eq_slider.value = sign.q;
            eq_slider.step = 0.1;
        }
        updateSliderBackground(eq_slider);
    });
    eqChart.drawEqLine();
}

function updateEQ_DB(index) {
    if (index != null) {
        const sign = chManager.current_chlist[0].sign_list[index];
        const db = document.getElementById(`eq_db_${index}`);
        db.disabled = !is_gain;
        db.value = sign.gain;
    } else {
        chManager.current_chlist[0].sign_list.forEach((sign, i) => {
            const db = document.getElementById(`eq_db_${i}`);
            db.disabled = !is_gain;
            db.value = sign.gain;
        });
    }
}

function updateEQ_Freq() {
    chManager.current_chlist[0].sign_list.forEach((sign, i) => {
        const freq = document.getElementById(`eq_freq_${i}`);
        freq.disabled = !is_freq;
        freq.value = sign.freq;
    });
}

function updateEQ_Q() {
    chManager.current_chlist[0].sign_list.forEach((sign, i) => {
        const q = document.getElementById(`eq_q_${i}`);
        q.disabled = !is_q;
        q.value = sign.q;
    });
}


function updatePASS(ishigh, { isall = false } = {}) {
    updatePASS_Freq(ishigh, { isall: isall });
    updatePASS_type(ishigh, { isall: isall });
    updatePASS_slope(ishigh, { isall: isall });
}

function updatePASS_Freq(ishigh, { isall = false } = {}) {
    const list = isall === true ? chManager.chlist : chManager.current_chlist;
    list.forEach((ch, i) => {
        const index = ch.num <= 0 ? 0 : ch.num - 1;
        const pass = ishigh ? ch.high_pass : ch.low_pass;
        const id = ishigh ? '#bg_high_pass' : '#bg_low_pass';
        const freq = document.querySelector(`${id} #input_${index}`);
        if (freq.value !== '' && parseInt(freq.value, 10) >= pass.min_freq && parseInt(freq.value, 10) <= pass.max_freq) {
            freq.value = pass.freq;
        }
    });
}

function updatePASS_type(ishigh, { isall = false } = {}) {
    const list = isall === true ? chManager.chlist : chManager.current_chlist;
    list.forEach((ch, i) => {
        const index = ch.num <= 0 ? 0 : ch.num - 1;
        const pass = ishigh ? ch.high_pass : ch.low_pass;
        const id = ishigh ? '#bg_high_pass' : '#bg_low_pass';
        const type = document.querySelector(`${id} #pass_type_${index}`);
        type.childNodes[0].textContent = pass.type.name;
    });
}

function updatePASS_slope(ishigh, { isall = false } = {}) {
    const list = isall === true ? chManager.chlist : chManager.current_chlist;
    list.forEach((ch, i) => {
        const index = ch.num <= 0 ? 0 : ch.num - 1;
        const pass = ishigh ? ch.high_pass : ch.low_pass;
        const id = ishigh ? '#bg_high_pass' : '#bg_low_pass';
        const slope = document.querySelector(`${id} #slope_${index}`);
        slope.childNodes[0].textContent = `${pass.type.slope}` + 'dB/Oct';
    });
}

function updateDB({ isall = false } = {}) {
    updateDB_db({ isall: isall });
    updateDB_Mute({ isall: isall });
}
function updateDB_db({ isall = false } = {}) {
    const list = isall === true ? chManager.chlist : chManager.current_chlist;
    list.forEach((ch, i) => {
        const index = ch.num <= 0 ? 0 : ch.num - 1;
        const slider = document.getElementById(`my_db_input_${index}`);
        const db = document.getElementById(`db_${index}`);
        const phase = document.getElementById(`my_ch_phase_${index}`);
        slider.value = ch.db;
        db.textContent = ch.db;
        phase.textContent = ch.phase ? '180°' : '0°';
        updateSliderBackground(slider, false);
    });
}

function updateDB_Mute({ isall = false } = {}) {
    const list = isall === true ? chManager.chlist : chManager.current_chlist;
    list.forEach((ch, i) => {
        const index = ch.num <= 0 ? 0 : ch.num - 1;
        const mute = document.getElementById(`ch_mute_${index}`);
        addSelected(mute, ch.mute)
    });
}

function updateDelay() {
    chManager.chlist.forEach((e, i) => {
        const input = document.getElementById('delay_input_' + `${i}`);
        input.value = DSP.getDelayValue(i);
    });
}

function updateMasterAll() {
    const db = document.getElementById('master_db');
    const mute = document.getElementById('master_mute');
    const slider = document.getElementById('verticalSlider');
    const ticksContainer = document.querySelector('.ticks');
    db.textContent = `${chManager.db}`;
    slider.value = chManager.db;
    toggleSelected(mute, chManager.mute);
    updateSliderBackground(slider);
    updateTicksColor(slider, ticksContainer);
}

///刷新从设备获取到音源后，更新合频弹窗页面
function updateSumAlert() {
    const curren_nav_title = chManager.current_source_list.map(($0) => {
        const list = origin_map.filter((el) => Object.values(el)[0] === $0);
        return Object.keys(list[0])[0];
    });
    const nav_list = document.querySelectorAll('.sum_source_div .nav_a');
    nav_list.forEach((e, i) => {
        const label = e.querySelector('.label');
        label.textContent = curren_nav_title[i];
    });
    addSumItems();
}

///更改选中的group
function changeSelectGroup(group_index) {
    DSP.selectGroup(group_index);
    changeSelectCH(chManager.chlist[group_index * 2]);
    updatePASS(true);
    updatePASS(false);
    updateDB();
}

///更改显示选中的通道
function changeSelectCH(ch) {
    if (ch.num < 1) {
        return;
    }
    const index = ch.num - 1;
    const group_index = index % 2 === 0 ? index / 2 : (index - 1) / 2;
    chManager.group_list.forEach((e, i) => {
        chManager.group_list[i] = group_index === i && chManager.group_list[i] ? true : false
        const bg_group = document.getElementById(`btn_group_${i}`);
        addSelected(bg_group, chManager.group_list[i]);
    })
    DSP.unitGroup(index);
    chManager.chlist.forEach(($0, i) => {
        const ch_name = document.getElementById(`ch_name_${i}`);
        addSelected(ch_name, $0.select);
    });
    updateEQ();
}


// 添加 高通.  |  低通相关
function addHighLowPassItems(ishigh) {
    const bg_pass = document.getElementById(ishigh ? 'bg_high_pass' : 'bg_low_pass');

    const template = document.getElementById('template_pass');
    const clone = template.content.cloneNode(true);
    const bg_pass_item = clone.getElementById('bg_pass_item');
    const title = clone.querySelector('.my_title1');
    title.textContent = ishigh ? 'HIGH PASS' : 'LOW PASS';

    const high_pass_ch_items = clone.querySelector('.bg_ch_items');
    const high_pass_template = clone.getElementById('template_ch_pass');
    chManager.chlist.forEach((ch, index) => {
        const pass_model = ishigh ? ch.high_pass : ch.low_pass;
        const clone2 = high_pass_template.content.cloneNode(true);
        const pass_item = clone2.querySelector('.ch_pass_item_div');
        const input = clone2.querySelector('input');
        const type = clone2.querySelector('.pass_type');
        const slope = clone2.querySelector('.slope');

        pass_item.id = `ch_pass_item_${index}`;
        type.id = `pass_type_${index}`;
        slope.id = `slope_${index}`;
        input.id = `input_${index}`;
        input.value = pass_model.freq;
        type.childNodes[0].textContent = pass_model.type.name;
        slope.childNodes[0].textContent = `${pass_model.type.slope}` + 'dB/Oct';

        ///鼠标停留在pass_item上
        pass_item.addEventListener('mouseenter', () => {

        });

        pass_item.addEventListener('mouseleave', () => {
            // pass_dropdown.style.display = 'none';
            // slope_dropdown.style.display = 'none';
        });

        input.onfocus = function () {
            input.dataset.oldValue = input.value;
            changeSelectCH(ch);
        }

        input.oninput = function (e) {
            let val = parseInt(e.target.value, 10);
            inputAction(val);
        }

        input.onblur = function (e) {
            let val = parseInt(e.target.value, 10);
            val = Math.min(Math.max(val, pass_model.min_freq), pass_model.max_freq);
            inputAction(val);
        }

        function inputAction(val) {
            // 与旧值比较（都转为字符串比较，以确保一致性）
            const oldVal = parseInt(input.dataset.oldValue, 10);
            input.dataset.oldValue = val;
            input.value = val;
            if (val === oldVal) return; // 没有变化则不处理
            DSP.updatePassFreq(ishigh, val);
            changeSelectCH(ch);
            updatePASS_Freq(ishigh);
        }

        ///点击弹出下拉框
        const typetextlist = ch.high_pass.types.map(($0) => $0.name);
        type.onclick = function (e) {
            e.stopPropagation();
            documentClick();
            changeSelectCH(ch);
            showDropdown(type, pass_dropdown, 'bottom');
            dropMenuHandle(pass_dropdown, (text, event, el) => {
                if (event.click) {
                    bg_pass.querySelector(`#pass_type_${ch.num - 1}`).childNodes[0].textContent = text;
                    const typeIndex = typetextlist.findIndex(($0) => $0 === text);
                    DSP.updateSlopeType(ishigh, typeIndex, pass_model.type.slope);
                    updatePASS_type(ishigh);
                    updatePASS_slope(ishigh);
                    changeSelectCH(ch);
                }
            });
        }

        slope.onclick = function (e) {
            e.stopPropagation();
            documentClick();
            showDropdown(slope, slope_dropdown, 'bottom');
            changeSelectCH(ch);
            dropMenuHandle(slope_dropdown, (text, event, el) => {
                if (event.click) {
                    bg_pass.querySelector(`#slope_${ch.num - 1}`).childNodes[0].textContent = `${pass_model.type.slope}` + 'dB/Oct';
                    DSP.updateSlope(ishigh, text);
                    updatePASS_slope(ishigh);
                    changeSelectCH(ch);
                }
            });
        }
        high_pass_ch_items.appendChild(pass_item);
    });
    bg_pass.appendChild(bg_pass_item);
}

// 添加音量
function addDbItems() {
    const db_ch_items = document.querySelector('#bg_phase .bg_ch_items');
    const db_template = document.getElementById('template_ch_db');

    initDbItems();
    function initDbItems() {
        ///清除
        document.querySelectorAll('#bg_phase .bg_ch_items .ch_db_item_div').forEach(item => item.remove());
        chManager.chlist.forEach((ch, index) => {
            const clone = db_template.content.cloneNode(true);
            const db_item = clone.querySelector('.ch_db_item_div');
            const phase = clone.querySelector('.my_ch_phase');
            const slider = clone.querySelector('.my_db_input');
            const db = clone.querySelector('span');
            const mute = clone.querySelector('.ch_mute');
            const ch_color = clone.querySelector('.ch_color');

            db_item.id = `ch_db_${index}`;
            phase.id = `my_ch_phase_${index}`;
            slider.id = `my_db_input_${index}`;
            db.id = `db_${index}`;
            mute.id = `ch_mute_${index}`;
            ch_color.id = `db_ch_color_${index}`;
            ch_color.style.background = ch.hex_line;
            db_ch_items.appendChild(db_item);

            ///正反相
            phase.textContent = ch.phase ? '180°' : '0°';
            phase.onclick = function (e) {
                changeSelectCH(ch);
                DSP.updatePhase(ch);
                chManager.current_chlist.forEach(($0) => {
                    document.getElementById(`my_ch_phase_${$0.num - 1}`).textContent = $0.phase ? '180°' : '0°';
                });
            }

            ///静音
            toggleSelected(mute, ch.mute);
            mute.onclick = function (e) {
                ch.mute = !ch.mute;
                changeSelectCH(ch);
                DSP.updateDB(ch.mute, ch.db);
                updateDB_Mute();
            }

            ///音量
            slider.max = ch.max_db;
            slider.min = ch.min_db;
            slider.value = ch.db;
            db.textContent = ch.db;
            updateSliderBackground(slider, false);
            slider.oninput = function (event) {
                ch.db = parseInt(event.target.value, 10);
                changeSelectCH(ch);
                DSP.updateDB(ch.mute, ch.db);
                updateDB_db();
            }
        });
    }
}

// 总音量静音相关
function addMasterDbItems() {
    const db = document.getElementById('master_db');
    const mute = document.getElementById('master_mute');
    const slider = document.getElementById('verticalSlider');
    const ticksContainer = document.querySelector('.ticks');
    const scale_left = document.getElementById('master_scale_left');
    const scale_right = document.getElementById('master_scale_right');

    toggleSelected(mute, chManager.mute);
    mute.addEventListener('click', () => {
        DSP.updateAllDB(!chManager.mute, chManager.db);
        toggleSelected(mute, chManager.mute);
    });

    ///给个初始化值，把滑动块的背景刻度颜色也同步
    slider.max = chManager.max_db;
    slider.min = chManager.min_db;
    slider.value = chManager.db;
    db.textContent = `${chManager.db}`;
    updateSliderBackground(slider);
    slider.addEventListener('input', () => {
        db.textContent = `${parseInt(slider.value, 10)}`;
        updateSliderBackground(slider);
        updateTicksColor(slider, ticksContainer);
        DSP.updateAllDB(chManager.mute, slider.value);
    });

    for (let i = 0; i < 40; i++) {
        const tick = document.createElement('div');
        ticksContainer.appendChild(tick);
    }
    //把滑动块的背景刻度颜色也同步
    updateTicksColor(slider, ticksContainer);

    var num = slider.max;
    for (let i = 0; i < (slider.max - slider.min) / 10 + 1; i++) {
        const span1 = document.createElement('span');
        const span2 = document.createElement('span');
        span1.style.fontSize = '12px';
        span2.style.fontSize = '12px';
        span1.textContent = num == slider.min ? 'OFF' : `${num} -`;
        span2.textContent = num == slider.min ? 'OFF' : `- ${num}`;
        num = num - 10;
        scale_left.appendChild(span1);
        scale_right.appendChild(span2);
    }
}

///添加合频相关
function addSumItems() {
    const bg_ml_message = document.querySelectorAll('.ml_message')[0];
    const alert = document.getElementById('channel_setup_alert');
    const cancel = document.getElementById('alert_cancel');
    const sum_grid = document.getElementById('sum_grid');
    const sum_reset = document.getElementById("sum_reset");
    cancel.addEventListener('click', () => hiddenAlert(bg_ml_message));
    let current_ch = chManager.current_chlist[0];
    sum_grid.style.gridTemplateColumns = `repeat(${Math.max(6, Math.ceil(chManager.chlist.length / 2))}, 1fr)`;
    sum_reset.onclick = function () {
        DSP.resetSUM();
        onclickSumItem(chManager.sum_list.length - 1);
    }

    ///添加外面大的item
    const observer = new MutationObserver(() => {
        const style = getComputedStyle(bg_ml_message);
        if (style.display !== 'none' && style.visibility !== 'hidden') {
            console.log('元素已被显示');
            chManager.current_source_list.forEach(($0) => updateInputSource($0));
            observer.disconnect(); // 触发一次就停止
        }
    });
    observer.observe(bg_ml_message, {
        attributes: true,
        attributeFilter: ['style', 'class']
    });

    ///添加输出通道
    addOutputItems();
    function addOutputItems(soureIndex) {
        const temp_index = chManager.current_source_list.last == SourceType.off ? 0 : chManager.current_source_list.length - 1;
        const change_source_index = soureIndex == null ? temp_index : soureIndex;
        ///清除
        document.querySelectorAll('#sum_grid .sum_item_container').forEach(item => item.remove());
        const template = document.getElementById('sum_template');
        chManager.chlist.forEach((ch, i) => {
            const clone = template.content.cloneNode(true);
            const sum_item_container = clone.querySelector('.sum_item_container');
            const sum_item = clone.querySelector('.sum_item');
            const ch_num = clone.querySelector('.sum_ch_name');

            sum_item_container.id = `sum_item_container_${i}`;
            sum_item.id = `sum_item_${i}`;
            sum_item.style.gridTemplateColumns = `repeat(${Math.ceil(ch.target_list.length / 2)}, 14px)`;
            ch_num.id = `sum_ch_name_${i}`;
            ch_num.textContent = `CH${i + 1}`;

            ///添加每个通道里面的item
            const length = chManager.current_source_list.length;
            ch.target_list.forEach((e, j) => {
                const cell = document.createElement('div');
                cell.className = 'sum_item_cell';
                if (e !== 1 || length <= 0) {
                    cell.textContent = '';
                } else if (chManager.current_source_list[change_source_index] === SourceType.rca) {
                    cell.textContent = `${j + 1}`;
                } else {
                    cell.textContent = j > 1 ? '' :(j % 2 === 0 ? 'L' : 'R');
                }
                sum_item.appendChild(cell);
            });
            sum_grid.appendChild(sum_item_container);
            sum_item_container.onclick = function () {
                current_ch = chManager.chlist[i];
                toggleExclusiveSelected(sum_item, document.querySelectorAll('.sum_item'));
                addinput();
            }
        });
    }

    //音源输入类型按钮
    showInputSource();
    function showInputSource() {
        const nav_list = document.querySelectorAll('.sum_source_div .nav_a');
        const sum_dropdown = document.getElementById('sum-dropdown');
        const ul = sum_dropdown.querySelector('ul');

        const opition1 = [SourceType.rca];
        const opition2 = [SourceType.aux, SourceType.bt];
        const opition3 = [SourceType.optical, SourceType.coaxial];

        nav_list.forEach((e, i) => {
            const isMain = i === 0;
            const label = e.querySelector('.label');
            e.onclick = function (event) {
                event.preventDefault();
                event.stopPropagation();
                sum_dropdown.style.display = '';
                ul.innerHTML = '';

                ///筛选条件
                function filtermap(target, obj) {
                    if (target === SourceType.off) {
                        return true;
                    } else if (opition1.includes(target) && !opition1.includes(obj)) {
                        return true;
                    } else if (opition2.includes(target) && !opition2.includes(obj)) {
                        return true;
                    } else if (opition3.includes(target) && !opition3.includes(obj)) {
                        return true;
                    }
                    return false;
                }

                let list = chManager.current_source_list.slice(0, 2);
                while (list.length < 2) list.push(SourceType.off);

                const main_map = origin_map.filter(($0) => filtermap(list[1], Object.values($0)[0]));
                const second_map = origin_map.filter(($0) => filtermap(list[0], Object.values($0)[0]));
                const main_keys = main_map.map(($0) => Object.keys($0)[0]);
                const second_keys = [...second_map.map(($0) => Object.keys($0)[0]), 'Off'];
                const main_values = main_map.map(($0) => Object.values($0)[0]);
                const second_values = [...second_map.map(($0) => Object.values($0)[0]), SourceType.off];

                ///生成新的列表
                const current_keys = isMain ? main_keys : second_keys;
                current_keys.forEach((text, i) => {
                    const li = document.createElement('li');
                    const button = document.createElement('button');
                    button.textContent = text;
                    li.appendChild(button);
                    ul.appendChild(li);
                });

                ///弹出下拉列表
                showDropdown(e, sum_dropdown, 'bottom');
                dropMenuHandle(sum_dropdown, (text, event, el, index) => {
                    if (!event.click) return;

                    ///主通道
                    if (isMain) {
                        label.textContent = main_keys[index];
                        list[0] = main_values[index];;
                        const type = list[0] === SourceType.off ? list.laset : list[0]
                        updateInputSource(type);
                    }
                    ///从通道
                    else {
                        label.textContent = second_keys[index];
                        list[1] = second_values[index];
                        const type = list[1] === SourceType.off ? list.first : list[1]
                        updateInputSource(type);
                    }
                    chManager.current_source_list = list;
                    showInputSumMode(isMain ? 0 : 1);
                    DSP.updateSource();
                });
            }
        });
    }

    ///更新不同音源，页面显示风格
    function updateInputSource(type) {
        switch (type) {
            case SourceType.rca:
                document.getElementById("sum_grid").style.display = "";
                document.getElementById("sum_l_r_div").style.display = "none";
                document.getElementById("sum_input_div").style.display = "";
                break;
            case SourceType.bt:
            case SourceType.usb:
            case SourceType.aux:
                document.getElementById("sum_grid").style.display = "";
                document.getElementById("sum_l_r_div").style.display = "";
                document.getElementById("sum_input_div").style.display = "none";
                break;
            case SourceType.optical:
            case SourceType.coaxial:
                document.getElementById("sum_grid").style.display = "";
                document.getElementById("sum_l_r_div").style.display = "";
                document.getElementById("sum_input_div").style.display = "none";
                break;
            default:
                break;
        }
    }

    ///sum类型
    showInputSumMode();
    function showInputSumMode(soureIndex) {
        const sum_mode = document.getElementById('sum_input_mode');
        const list = sum_mode.querySelectorAll('.nav_a');
        const matchedIndex = chManager.sum_list.findIndex(el => el === chManager.current_sum);
        onclickSumItem(matchedIndex, soureIndex);

        list.forEach((li, index) => {
            li.onclick = function (e) {
                const anchor = e.target.closest('.nav_a');
                if (!anchor) return;
                e.preventDefault();
                DSP.updateSUMType(chManager.sum_list[index]);
                onclickSumItem(index);
            }
        })
    }

    ///点击custom更新UI的方法
    function onclickSumItem(sumIndex, soureIndex) {
        const sum_mode = document.getElementById('sum_input_mode');
        const list = sum_mode.querySelectorAll('.nav_a');
        toggleAddSelect(list[sumIndex], list);
        addinput();
        addOutputItems(soureIndex);
    }

    ///添加输入通道选择
    function addinput() {
        ///清除
        document.querySelectorAll('#sum_input_select .sum_l_r_item').forEach(item => item.remove());
        const sum_input_select = document.getElementById('sum_input_select');
        const sum_input_template = document.getElementById('sum_input_select_template');
        sum_input_select.style.gridTemplateColumns = `repeat(${Math.ceil(current_ch.target_list.length / 2)}, 50px)`;
        current_ch.target_list.forEach((el, index) => {
            const clone = sum_input_template.content.cloneNode(true);
            const lbl = clone.querySelector('.sum_l_r_item');
            const input = lbl.querySelector('input');
            lbl.id = `sum_l_r_item_${index}`;
            const inputId = `sum_ch_${index + 1}`;
            lbl.htmlFor = inputId; // 修正 for 属性
            input.id = inputId; // 修正 input id
            input.value = `CH${index + 1}`;
            input.checked = el != 0;
            lbl.lastChild.textContent = `CH${index + 1}`;
            sum_input_select.appendChild(lbl);
            input.onclick = function (e) {
                const sum_item = document.querySelector(`#sum_item_${current_ch.num - 1}`);
                if (sum_item === null || !sum_item.classList.contains('selected')) {
                    myToast.show('请先选择一个输出通道');
                    e.preventDefault(); // ✅ 真正阻止 checkbox 状态变化
                    return false;
                }
                DSP.updateSum(current_ch, index);
                const num = e.target.checked ? index + 1 : 0;
                document.querySelectorAll(`#channel_setup_alert #sum_item_${current_ch.num - 1} .sum_item_cell`)[index].textContent = num === 0 ? '' : num;
            }
        });


        ///l/r
        document.querySelectorAll('#sum_l_r_div .sum_l_r_item').forEach((item, i) => {
            const input = item.querySelector('input');
            input.checked = current_ch.target_list[i] != 0;
            input.onclick = function (e) {
                const sum_item = document.querySelector(`#sum_item_${current_ch.num - 1}`);
                if (sum_item === null || !sum_item.classList.contains('selected')) {
                    myToast.show('请先选择一个输出通道');
                    e.preventDefault(); // ✅ 真正阻止 checkbox 状态变化
                    return false;
                }
                const index = input.value === 'L' ? 0 : 1;
                const text = input.checked ? input.value : '';
                DSP.updateSum(current_ch, index);
                // const num = e.target.checked ? index + 1 : 0;
                document.querySelectorAll(`#channel_setup_alert #sum_item_${current_ch.num - 1} .sum_item_cell`)[index].textContent = input.checked ? text : '';
            }
        });

        current_ch.target_list.forEach((el, index) => {


        });
    }
}

// 显示保存下拉菜单
function showSaveDropMenu(anchor) {
    showDropdown(anchor, save_dropdown, 'bottom', 130);
    dropMenuHandle(save_dropdown, async (text, event, el) => {
        switch (text) {
            case 'Save to File':
                switch (true) {
                    case event.click:
                        DSP.saveFile();
                        break;
                    case event.in:
                        preset_dropleft.style.display = 'none';
                        break;
                    case event.out:
                        break;
                }
                break;
            case 'Save to Device':
                switch (true) {
                    case event.click:
                        break;
                    case event.in:
                        preset_dropleft.style.display = 'none';
                        showDropdown(el, preset_dropleft, 'right');
                        break;
                    case event.out:
                        break;
                }
                break;
            default:
                break;
        }
    });
}

// 显示加载下拉菜单
function showLoadDropMenu(anchor) {
    showDropdown(anchor, load_dropdown, 'bottom', 150);
    dropMenuHandle(load_dropdown, async (text, event, el) => {
        switch (text) {
            case 'Load from File':
                switch (true) {
                    case event.click:
                        await DSP.openFile();
                        updateAll();
                        break;
                    case event.in:
                        preset_dropleft.style.display = 'none';
                        updateEQ();
                        updatePASS(true);
                        updatePASS(false);
                        updateDB();
                        break;
                    case event.out:
                        break;
                }
                break;
            case 'Load from Present':
                switch (true) {
                    case event.click:
                        break;
                    case event.in:
                        preset_dropleft.style.display = '';
                        const buttonlist = preset_dropleft.querySelectorAll('ul li button');
                        buttonlist.forEach(($0, i) => $0.textContent = chManager.config.effectKeys[i]);
                        buttonlist.forEach((e, i) => addSelected(e, effectIndex === i));
                        showEffectDropMenu(el);
                        break;
                    case event.out:
                        break;
                }
                break;
            default:
                break;
        }
    });
}

///eq预设值
function showEffectDropMenu(anchor) {
    showDropdown(anchor, preset_dropleft, 'right');
    dropMenuHandle(preset_dropleft, (text, event, el) => {
        if (event.click) {
            const matchedIndex = chManager.config.effectKeys.findIndex(el => el === text);
            effectIndex = matchedIndex;
            const buttonlist = preset_dropleft.querySelectorAll('ul li button');
            buttonlist.forEach((e, i) => addSelected(e, effectIndex === i));
            DSP.setPresentEQ(effectIndex);
            updateEQ();
        }
    });
}

// 显示reseteq下拉菜单
function showResetDropMenu(anchor) {
    showDropdown(anchor, reset_dropdown, 'bottom');
    dropMenuHandle(reset_dropdown, (text, event, el) => {
        if (event.click) {
            DSP.resetEQ(text === 'Reset All EQ');
            if (text === 'Reset All EQ') {
                const bypass = document.querySelector('#nav_left #nav_bypass');
                const spanLabel = bypass.querySelector('.label'); // 查找子元素中 class="label" 的 span
                spanLabel.textContent = 'Bypass';
                addSelected(bypass, false);
            }
            updatePASS(true, { isall: true });
            updatePASS(false, { isall: true });
            updateEQ();
            effectIndex = -1;
        }
    });
}

// 显示设置下拉菜单
function showSettingDropMenu(anchor) {
    showDropdown(anchor, setting_dropdown, 'bottom_left', 150);
    dropMenuHandle(setting_dropdown, (text, event, el) => {
        switch (text) {
            case '中文':
                switch (true) {
                    case event.click:
                        break;
                    case event.in:
                        break;
                    case event.out:
                        break;
                }
                break;
            case 'Firmware Update':
                switch (true) {
                    case event.click:
                        break;
                    case event.in:
                        break;
                    case event.out:
                        break;
                }
                break;
            default:
                break;
        }
    });
}

// 显示噪声下拉菜单
function showNoiseDropMenu(anchor) {
    showDropdown(anchor, noise_dropdown, 'bottom');
    dropMenuHandle(noise_dropdown, (text, event, el) => {
        if (event.click) {
            let noise = text === 'close' ? 0 : parseInt(text.replace(/[^\d]/g, ''), 10);
            const list = noise_dropdown.querySelectorAll('li button');
            list.forEach(($0) => toggleExclusiveSelected(list[noise], list));
            const nav_noise = document.querySelector('nav #nav_left #nav_noise .label');
            nav_noise.textContent = noise === 0 ? 'Noise' : `level${noise}`;
            DSP.updateNoise(noise);
        }
    });
}

// 统一处理下拉菜单的子选项的动作
function dropMenuHandle(dropMenu, handler) {
    const li_buttons = dropMenu.querySelectorAll('button');
    li_buttons.forEach((el, index) => {
        const text = el.textContent.trim();
        ///点击某个li选项 ⚠️⚠️⚠️，不使用addEventListener。会重复调用
        el.onclick = function (e) {
            // console.log('鼠标点击在按钮上。=== ', text);
            handler && handler(text, { click: true, in: false, out: false }, el, index);
        }
        el.onmouseenter = function (e) {
            e.stopPropagation()
            handler && handler(text, { click: false, in: true, out: false }, el, index);
            // console.log('鼠标悬停在按钮上。===', text);
        }
        el.onmouseleave = function (e) {
            e.stopPropagation()
            handler && handler(text, { click: false, in: false, out: true }, el, index);
            // console.log('鼠标离开按钮。=== ', text);
        }
    });
}
// 更新滑块的背景颜色
function updateSliderBackground(slider, isVertical = true) {
    const value = parseFloat(slider.value);
    const min = parseFloat(slider.min);
    const max = parseFloat(slider.max);
    const percentage = calculatePercentage(value, min, max);
    if (isVertical) {
        slider.style.background = `
        linear-gradient(to top, #0B84FF 0%, #5AC8F4 50%, #67D4CF 100%)
     #1C1C1E`;
        slider.style.backgroundSize = `100% ${percentage}%`;
        slider.style.backgroundPosition = `bottom`;
    } else {
        slider.style.background = `
        linear-gradient(to right, #0B84FF 0%, #5AC8F4 50%, #67D4CF 100%)
     #1C1C1E`;
        slider.style.backgroundSize = `${percentage}% 100%`;
        slider.style.backgroundPosition = `left`;
    }
    slider.style.backgroundRepeat = `no-repeat`;
    const final_v = max - value + min;
    return final_v;
}

// 计算滑动的百分比
function calculatePercentage(value, min, max) {
    return ((value - min) / (max - min)) * 100;
}

///更新master总音量后面的刻度背景颜色
function updateTicksColor(slider, ticksContainer) {
    const ticks = Array.from(ticksContainer.children).reverse();// 直接拿所有tick元素，取倒叙 
    const totalTicks = ticks.length;

    const min = parseFloat(slider.min);
    const max = parseFloat(slider.max);
    const value = parseFloat(slider.value);
    // 计算滑动比例
    const ratio = calculatePercentage(value, min, max) / 100;
    const highlightCount = Math.round(ratio * totalTicks);

    const activeColor = '#0B84FF';
    const inactiveColor = '#888';

    for (let i = 0; i < totalTicks; i++) {
        if (i < highlightCount) {
            ticks[i].style.backgroundColor = activeColor;
        } else {
            ticks[i].style.backgroundColor = inactiveColor;
        }
    }
}


///document点击空白处
function documentClick(event) {
    // 如果点击的目标是 导航栏或它的子元素，则过滤
    const insideNav = event?.target.closest('nav');
    // const insideAlert = event?.target.parentElement.parentElement.parentElement.parentElement.className === 'sum_source_div';
    if (insideNav) {
        return;
    }
    hiddenDropdown();
    resetNav();
}

///点击空白处隐藏下拉框
function hiddenDropdown() {
    document.querySelectorAll('.dropdown-menu').forEach(($0) => $0.style.display = 'none');
}

// 重置导航栏状态
function resetNav() {
    ///同时，顺带重置导航按钮
    const navbar = document.getElementById('nav_left');
    const list = navbar.querySelectorAll('.nav_a');
    // 过滤掉 nav_bypass
    const filteredList = Array.from(list).filter(nav => nav.id !== 'nav_bypass' && nav.id !== 'nav_link');
    // 执行一次即可
    toggleExclusiveSelected(null, filteredList);

}
///隐藏弹窗，和，重置导航栏的状态
function hiddenAlert(alert, event) {
    // 如果点击的目标是 #channel_setup_alert 或它的子元素，则不关闭
    const insideAlert = event?.target.closest('#channel_setup_alert');
    if (insideAlert) {
        return;
    }
    alert.style.display = 'none';
}

///统一切换按钮状态
function toggleExclusiveSelected(currentEl, list) {
    list.forEach(el => {
        var arrow = el.querySelector('.icon_arrow');
        if (arrow != null) {
            const isCurrent = currentEl == el;
            const isUp = arrow.dataset.state === 'up';
            const shouldBeUp = isCurrent && !isUp;
            arrow.src = '../resources/' + (shouldBeUp ? 'arrow_up.png' : 'arrow_down.png');
            arrow.dataset.state = shouldBeUp ? 'up' : 'down';
        }
        toggleSelected(el, currentEl == el);
    });
}

///统一切换按钮状态，并且，只能 点击自己取消选中状态，不能便利取消
function toggleAddSelect(currentEl, list) {
    list.forEach(el => {
        var arrow = el.querySelector('.icon_arrow');
        if (arrow != null) {
            const isCurrent = currentEl == el;
            const isUp = arrow.dataset.state === 'up';
            const shouldBeUp = isCurrent && !isUp;
            arrow.src = '../resources/' + (shouldBeUp ? 'arrow_up.png' : 'arrow_down.png');
            arrow.dataset.state = shouldBeUp ? 'up' : 'down';
        }
        addSelected(el, currentEl === el);
    });
}
